<!--商品优惠券-->
<meta charset="utf-8"/>
<div class="row">
  <div class="col-xs-12">
    <div class="row">
      <div class="col-xs-12">
        <div style="height:36px;margin-top:2px">
          <table class="no-border" style="display:inline">
            <tr>
              <td permission='coupon_btn_listData' style="padding-right:6px;display:none">
                商品名称
              </td>
              <td permission='coupon_btn_listData' style="display:none">
                <input type="text" id="key_goods_name" class="form-control search-query" placeholder="输入商品名称" style="width:200px"/>
              </td>
              <td permission='coupon_btn_listData' style="display:none">
                <div class="input-group">
                  <span class="input-group-btn"><button type="button" class="btn btn-inverse btn-white" id="btnSearch" title="搜索查询"><span class="ace-icon fa fa-search bigger-110"></span>搜索</button></span>
                </div>
              </td>
              <td permission='coupon_btn_listData' style="display:none" class="hidden-480">
                <div class="input-group">
                  <span class="input-group-btn"><button type="button" class="btn btn-inverse btn-white" id="btnReset" title="重置清空搜索关键字"><span class="ace-icon fa fa-undo bigger-110"></span>重置</button></span>
                </div>
              </td>
            </tr>
          </table>
          <div class="hidden-480 pull-right tableTools-container" permission='coupon_btn_listData' style="display:none;margin-bottom:2px"></div>
        </div>
        <table id="tableListCoupon" class="table table-striped table-bordered table-hover">
          <tbody>
          <tr>
            <td style="text-align:center;height:37px">正在加载……</td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<div id="div_coupon_edit" style="display:none;">
  <div style="height:36px;line-height:36px;padding-left:4px">
    全国默认的优惠券：<span id="coupon_default">0</span>
  </div>
  <form class="form-horizontal" id="form_coupon_edit" role="form">
    <table id="tableCouponEdit" class="tabletrtd">
      <thead>
        <tr>
          <th style="width:346px;max-width:340px;">行政区域</th>
          <th>发放数量</th>
          <th style="width:64px;" class="text-center">选项</th>
        </tr>
      </thead>
      <tbody>
      <tr>
        <td style="width:416px;max-width:410px;text-align:center;">暂无绑定行政区域</td>
        <td><input type="text" class="form-control" style="border:none" readonly="readonly"/></td>
        <td style="width:64px;" class="text-center"></td>
      </tr>
      </tbody>
    </table>
  </form>
</div>
<div id="divKeyColumns" style="display:none;padding:1px 0px;"></div>
<div style="display:none;">
  <input type="hidden" id="coupon_btn_listData"/>
  <input type="hidden" id="coupon_btn_add"/>
  <input type="hidden" id="coupon_row_edit"/>
  <input type="hidden" id="coupon_row_queryById"/>
</div>
<div style="display:none;padding-top:4px" id="div_area_tree">
  <ul id="ulTreeCoupon" class="ztree" style="padding:0px;"></ul>
</div>
<script type="text/javascript">
  ;(function($){
    var tableDom = '#tableListCoupon';
    var urlRoute = '/coupon/';/*请求controller层的url*/
    var getList = urlRoute + 'listData';/*获取数据列表*/
    var urlAdd = urlRoute + 'add';/*新增*/
    var urlEdit = urlRoute + 'edit';/*编辑*/
    var urlDel = urlRoute + 'delCoupon';/*删除商品优惠券发放规则*/
    var urlQueryById = urlRoute + 'queryById';/*根据id查询对应的数据*/
    var objzTreeCoupon = null;//ztree对象
    var openFlag = false;//是否是弹窗标识,重要!!!
    var domTreeCoupon = 'ulTreeCoupon';//ztree的dom节点
    var ztreeConfigCoupon = areaDept.initRelevance({
      url : '/coupon/getCouponTree',//此url可以动态赋值,ztreeConfigCoupon.async.url = urlPrefix + '/coupon/getCouponTree?goodsId=';在初始化之前赋值
      param : ['kid'],
      dataFilter : function(data){},
      callback : {
        onClick : function(event,treeId,node){},
        beforeAsync : function(treeId,node){
          if(node == undefined){//视情况是否开启,若是一加载页面右边就显示的话则无需开启
            self.layerIndex = layerFn.loading('正在处理……');
          }
        },
        onAsyncSuccess : function(event,treeId,node,data){
          if(node == undefined){
            layerFn.closeIndex(self.layerIndex);
          }
          if(openFlag){
            openFlag = false;
            thisPage.succeedDialog();//步骤②,仅弹窗1次
          }
        },
        beforeClick : function(treeId,node,clickFlag){
          return false;//true时点击选中文本
        },
        onAsyncError : function(event,treeId,node,XMLHttpRequest){
          layerFn.closeIndex(self.layerIndex);
          if(node == undefined){//此时ztree节点尚未生成
            layerFn.alert('连接服务器失败',AppKey.code.code199);
          }else{
            //thisPage.ztreeErrorCoupon('连接服务器失败');
            layerFn.handleResult('连接服务器失败',AppKey.code.code199,-1);
          }
        }
      }
    });
    var thisTable = null;
    thisPage = {
      init : function(){
        this.initTable();
        this.addEvent();
      },
      initDom : function(){},
      //每次调用都是刷新
      initTree : function(){
        authHandler('coupon_btn_tree', function(){
          objzTreeCoupon = $.fn.zTree.init($("#"+domTreeCoupon),ztreeConfigCoupon);
        }, function(){
          thisPage.ztreeErrorCoupon('暂无访问权限');
        });
      },
      ztreeErrorCoupon : function(msg){
        msg = (msg == null || msg == '') ? '获取数据失败' : msg;
        $("#"+domTreeCoupon).html("<li style='margin-top:2px;margin-left:4px'><span>"+msg+"</span></li>");
      },
      addEvent : function(){
        //搜索按钮
        $('#btnSearch').on('click', function(){
          thisPage.search(true);
        });
        //重置按钮
        $('#btnReset').on('click', function(){
          $('#key_goods_name').val('');
        });
        //按钮组-自定义显示列
        $('#iconColumn').parent().parent().on('click', function(){
          pageDataTable.columnCustom(thisTable, tableDom,'#divKeyColumns');
        });
        //按钮组-搜索
        $('#iconRefresh').parent().parent().on('click', function(){
          thisPage.search(true);
        });
      },
      initTable : function(){
        var optsVisible = getOptsVisible('coupon_row');//确定是否要显示操作选项,若是多个按钮权限时以逗号,隔开
        var aoColumns = [];
        aoColumns.push({
          data : "contract_name",
          sortable : false,
          title : "商品名称"
        });
        aoColumns.push({
          data : "goodsType",
          sortable : false,
          title : "商品类型"
        });
        aoColumns.push({
          data : "bottles",
          width : "120px",
          sortable : false,
          class : 'text-center',
          title : "每件瓶数"
        });
        aoColumns.push({
          data : "coupon",
          width : "130px",
          class : 'text-center',
          sortable : false,
          title : "默认优惠券数量"
        });
        aoColumns.push({
          data : "valid",
          sortable : false,
          width : "110px",
          class : 'text-center',
          title : "销售状态",
          className : 'hidden-480',
          render : function(value,type,row,meta){
            if(value){
              switch (value){
                case 1:
                  return "未下架";
                case 2:
                  return "已下架";
                default:
                  return "";
              }
            }else{
              return "";
            }
          }
        });
        aoColumns.push({
          data : "deleted",
          sortable : false,
          width : "110px",
          class : 'text-center',
          title : "显示状态",
          render : function(value,type,row,meta){
            if(value){
              switch (value){
                case 0:
                  return "隐藏";
                case 1:
                  return "显示";
                default:
                  return "";
              }
            }else{
              return "";
            }
          }
        });
        if(optsVisible){
          aoColumns.push({
            data : "_goods_id_",
            width : "88px",
            class : 'text-center',
            title : "<label style='color:#000' title='单行操作'>操作选项</label>",/*此处的字‘操作选项’请勿修改,此处的文字还有其它用途*/
            sortable : false
          });
        }
        var columnDefs = [];
        if(optsVisible){//是否来显示某列
          columnDefs.push({
            targets : -1,
            render : function(value,type,row,meta){
              return "<a title='区域设置|编辑及对应的优惠券信息' href='javascript:thisPage.rowArea("+ meta.row +");' style='outline:none;text-decoration:none;color:#3b8cff;display:none' permission='coupon_btn_add'>区域</a><a title='编辑已存在的优惠券信息' class='hidden-480' href='javascript:thisPage.rowEdit("+ meta.row +");' style='outline:none;text-decoration:none;color:#f00;margin-left:6px;display:none' permission='coupon_row_edit'>编辑</a>";
            }
          });
        }
        columnDefs.push({
          targets : [0,1,2,3,4],
          render : function(value,type,row,meta){
            return pageDataTable.formatColumn(value);
          }
        });
        columnDefs.push({
          visible : false,//列的隐藏显示
          targets : []//指定列索引
        });
        thisTable = pageDataTable.initDataTable({
          tableDom : tableDom,
          sAjaxSource : getList,
          fnServerParams : function(params){
            params.push(
              {"name":"goods_name","value":winFn.getDomValue('#key_goods_name')}
            );
          },
          aoColumns : aoColumns,
          columnDefs : columnDefs,
          complete : function(settings,data){},//仅执行一次
          footer : function(data,start,end,thLength){},//每次都会执行
          selected : function(selected){}
        });
        pageDataTable.buttons(thisTable);
        pageDataTable.action(thisTable);
        pageDataTable.select(thisTable, tableDom);
        pageDataTable.tooltip();
        $('.dataTables_scroll .dataTables_scrollBody').removeAttr('style');//解决dataTable表头下拉框被tbody遮挡
      },
      //是否是搜索,是则搜索时则返回到第一页
      search : function(search){
        if(verifyFn.inputCheck('#coupon_btn_listData','没有操作权限')) return;
        $(tableDom + '_wrapper table input[type=checkbox]').prop('checked',false);//此行不需要,因为搜索时表格已重新渲染
        if(search){
          $(tableDom).DataTable().ajax.reload();//编辑时成功会重载所有接口数据，返回到第一页
        }else{
          $(tableDom).DataTable().ajax.reload(null,false);//编辑时成功重新加载表数据(分页页码保留);
        }
      },
      resetForm : function(){
        winFn.clearFormData('#form_coupon_edit');
      },
      edit : function(kid){
        if(verifyFn.inputCheck('#coupon_row_queryById','没有操作权限')) return;
        layerFn.queryByIdHint(urlQueryById,kid,function(data){
          $('#coupon_default').text(data.data.coupon);
          if(data.data.list){
            self.formData = data.data.list;
          }else{
            self.formData = null;//置空
          }
          thisPage.openDialog(kid);
        });
      },
      //步骤③,成功后弹窗,仅弹窗1次
      succeedDialog : function(){
        var btn = self.formData != null ? '<span title="查看已绑定的区域及优惠券" style="color:#f84009;">详情</span>' : null;
        self.succeedIndex = layerFn.addOrEdit('选择区域位置','#div_area_tree',['550px','500px'],function(indexLayero){
          var nodes = objzTreeCoupon.getCheckedNodes(true);
          var list = [];
          if(nodes.length > 0){
            for(var a=0;a<nodes.length;a++){
              var obj = nodes[a];
              var json = {};
              json['kid'] = obj.kid;
              json['name'] = obj.name;
              json['pName'] = obj.pName;
              json['grade'] = obj.grade;
              json['quantity'] = obj.quantity;
              json['goods_id'] = obj.goods_id;
              list.push(json);
            }
          }
          thisPage.buildTr(list,true,true,false);
        },btn,function(indexLayero){
          if(verifyFn.inputCheck('#coupon_row_queryById','没有操作权限')) return;
          layerFn.queryByIdHint(urlQueryById,self.areaGoodsId,function(data){
            $('#coupon_default').text(data.data.coupon);
            if(data.data.list){
              thisPage.buildTr(data.data.list,false,false,true);
            }else{
              thisPage.buildTr([],false,false,true);
            }
          });
        });
        $('#layui-layer'+self.succeedIndex+' a.layui-layer-btn0').text('确定');
        $('#layui-layer'+self.succeedIndex+' a.layui-layer-btn1').text('关闭');
      },
      //步骤①,请求数据准备初始化树形列表
      openDialog : function(goodsId){
        openFlag = true;
        ztreeConfigCoupon.async.url = urlPrefix + '/coupon/getCouponTree?goodsId='+goodsId;
        thisPage.initTree();//初始化树形菜单
      },
      buildTr : function(list,selected,isAdd,disabled){//selected为true时是从树形菜单的打开的
        var html = '';
        if(selected){
          if(self.formData){
            if(list.length > 0){
              html += thisPage.handlerForm(list,self.formData);//处理已存在的
            }else{
              html += thisPage.handlerForm(self.formData,[]);//之前已添加过的,重新打开且又未选项任何数据
            }
          }else{
            if(list.length > 0){
              html += thisPage.handlerForm(list,[]);
            }else{
              html += thisPage.buildEmpty();
            }
          }
        }else{
          if(list.length > 0){
            html += thisPage.handlerForm(list,[]);
          }else{
            html += thisPage.buildEmpty();
          }
        }
        $('#tableCouponEdit tbody').html(html);
        self.formIndex = layerFn.addOrEdit('配置优惠券信息','#div_coupon_edit',['540px','490px'],function(indexLayero,layero){
          if(isAdd){
            if(verifyFn.inputCheck('#coupon_btn_add','没有新增权限')) return;
          }else{
            if(verifyFn.inputCheck('#coupon_row_edit','没有编辑权限')) return;
          }
          var params = {
            goods_id : self.areaGoodsId,
          };
          var values = [];
          $("input[id^='quantity_']").each(function(){
            var inputId = $(this).attr('id');
            var quantity = $(this).val();
            var goods_id = $('#'+inputId).attr('editvalue');//编辑时才存在
            var area_id = $('#'+inputId).attr('areaid');
            var json = {};
            if(quantity != null && quantity.length > 0){
              json['quantity'] = quantity;
            }
            if(goods_id != null && goods_id.length > 0){
              json['goods_id'] = goods_id;//编辑时才存在
            }
            if(area_id != null && area_id.length > 0){
              json['area_id'] = area_id;
            }
            json['type'] = $('#'+inputId).attr('grade');//区域等级,1,2,3,4,比如特殊区域的东莞市下的没有区直接到镇(所以3或4都是区县级)
            values.push(json);
          });
          params['values'] = JSON.stringify(values);
          var uri = isAdd ? urlAdd : urlEdit;
          layerFn.submit(uri,params,function(data){
            if(AppKey.code.code200 == data.code){
              if(self.succeedIndex){
                layer.close(self.succeedIndex);
              }
              layer.close(indexLayero);
            }
            layerFn.handleResult(data.msg,data.code);
          });
        });
        $('#layui-layer'+self.formIndex+' a.layui-layer-btn0').text('保存');
        if(disabled || list.length == 0){//若有问题把` || list.length == 0`删除即可
          $('#layui-layer' + self.formIndex + ' a.layui-layer-btn1').text('关闭').attr('title','关闭窗口');
          $('#layui-layer'+self.formIndex+' a.layui-layer-btn0').css('display','none');
        }
      },
      //两个数组合并
      handlerForm : function(lists,results){
        var containers = {};
        if(results.length > 0 && lists.length > 0){
          for(var f=0;f<lists.length;f++){
            var kid_ = lists[f].kid;
            containers[kid_] = lists[f];
          }
          for(var c=0;c<results.length;c++){
            var _kid = results[c].kid;
            containers[_kid] = results[c];//因为json的特点后面的会把前面的替换,所以是我们想要的效果,替换后再取出来
          }
        }
        var list = [];
        var index = 0;
        for(key in containers){
          index++;
          list.push(containers[key]);
        }
        list = index > 0 ? list : lists;
        var html = '';
        for(var b=0;b<list.length;b++){
          var obj = list[b];
          var goodsId = obj.goods_id;
          var is = obj.goods_id || false;//存在属性 editvalue 就是编辑
          var grade = obj.grade || false;//新增时才有值
          var kid = obj.kid;//区域id
          var pName = obj.pName || '';
          var quantity = obj.quantity || '';
          html += '<tr>';
          html += '<td style="width:346px;max-width:340px;text-align:left;" title="'+pName+obj.name+'">'+obj.name+'</td>';
          html += '<td><input type="text" '+(is ? 'editvalue="'+goodsId+'"' : '')+' '+(is ? 'value="'+quantity+'"' : '')+' '+(grade ? 'grade="'+obj.grade+'"' : '')+' areaid="'+kid+'" id="quantity_'+kid+'" placeholder="数量(为空时则禁用)" class="form-control" style="border:none" maxlength="10" title="发放数量（值为空时不送不发放）" oninput="value=value.replace(/[^\\d]/g,\'\')"/></td>';
          var optsDel = getOptsVisible('coupon_row_del');
          if(is && optsDel){//验证是否显示删除按钮
            html += '<td title="删除当前行" style="width:64px;" class="text-center"><a href="javascript:thisPage.rowCouponDel(\''+obj.goods_id+'\',\''+obj.kid+'\',\''+pName+obj.name+'\');" style="text-decoration: none;outline:none;color:#f00">删除</a></td>';
          }else{
            html += '<td style="width:64px;" class="text-center"></td>';
          }
          html += '</tr>';
        }
        return html;
      },
      buildEmpty : function(){
        var html = '';
        html += '<tr>';
        html += '<td style="width:416px;max-width:410px;text-align:center;">暂无绑定行政区域</td>';
        html += '<td><input type="text" class="form-control" style="border:none" readonly="readonly"/></td>';
        html += '<td style="width:64px;" class="text-center"></td>';
        html += '</tr>';
        return html;
      },
      rowArea : function(rowIndex){
        if(verifyFn.inputCheck('#coupon_btn_add','没有操作权限')) return;
        var row = thisTable.row(rowIndex).data();
        self.areaGoodsId = row.kid;//动态赋值
        thisPage.edit(row.kid);
      },
      rowEdit : function(rowIndex){
        self.formData = null;//置空
        if(verifyFn.inputCheck('#coupon_row_queryById','没有操作权限')) return;
        var row = thisTable.row(rowIndex).data();
        self.areaGoodsId = row.kid;//动态赋值
        layerFn.queryByIdHint(urlQueryById,row.kid,function(data){
          $('#coupon_default').text(data.data.coupon);
          if(data.data.list){
            thisPage.buildTr(data.data.list,false,false,false);
          }else{
            thisPage.buildTr([],false,false,true);
          }
        });
      },
      rowCouponDel : function(goodsId,areaId,areaName){
        authHandler('coupon_row_del',function(){
          layerFn.confirm('确定要删除['+areaName+']的优惠券规则吗？',function(){
            layerFn.submit(urlDel,{goodsId:goodsId,areaId:areaId},function(data){
              layerFn.closedAll();
              layerFn.handleResult(data.msg,data.code);
            });
          });
        },function(){
          layerFn.alert('没有删除权限',AppKey.code.code199);
        });
      },
      //查看隐藏部分是全部内容,用法 render : function(value,type,row,meta){return thisPage.rowColumnView(value);}
      rowColumnView : function(value){
        if(value == null || value == undefined || value == '') return '';
        value = typeof value === 'string' ? value.replace(/</g, '&lt;').replace(/"/g, '&quot;') : value;//如果提示SyntaxError: expected expression, got '>'错误则注释掉即可
        var len = value.length;
        if(len > 30){
          return "<a href='javascript:layerFn.viewValue(\""+value+"\",\"430px\");' title='点击查看详情' style='outline:none;text-decoration:none;'>"+value.substring(0,30)+"…</a>";
        }else{
          return value;
        }
      },
      complete : function(data,index,search){
        try{
          if(index){
            layerFn.closeIndex(index);
          }
          if(search){
            thisPage.search();
          }
          if(data){
            layerFn.handleResult(data.msg,data.code);
          }
        }catch(e){}
      }
    };
    thisPage.init();
    $('script').remove();
  })(jQuery);
</script>